package com.ctms.system.service.impl;

import com.ctms.common.utils.ShiroUtils;
import com.ctms.system.dao.CourseMapper;
import com.ctms.system.domain.CourseDO;
import com.ctms.system.domain.UserCourseDo;
import com.ctms.system.domain.UserDO;
import com.ctms.system.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    CourseMapper courseMapper;

    @Override
    public List<CourseDO> selectAllCourse(Map<String, Object> params) {
        return courseMapper.selectAllCourse(params);
    }

    @Override
    public int count(Map<String, Object> params) {
        return courseMapper.count(params);
    }

    @Override
    public int insert(CourseDO courseDO) {
        return courseMapper.insert(courseDO);
    }

    @Override
    public int deleteCourse(Integer cid) {
        CourseDO courseDO = courseMapper.selectById(cid);
        String teacher = courseDO.getCourseTeacher();
        String[] teacherId = teacher.split(",");
        UserDO userDO = ShiroUtils.getUser();
        int flag=0;
        int userId = Integer.parseInt(Long.toString(userDO.getUserId()));
        for (int i=0;i<teacherId.length;i++){
            int temp = Integer.parseInt(teacherId[i]);
            if (temp == userId) flag++;
        }
        if (flag > 0){
            courseMapper.deleteCourse(cid);
            String name=courseMapper.selectCourseNameByCid(cid);
            if (name != null){
                courseMapper.deleteUserCourse(name);
            }
            return 1;
        }else {
            return -1;
        }
    }

    @Override
    public String selectCourseNameByCid(Integer cid) {
        return courseMapper.selectCourseNameByCid(cid);
    }

    @Override
    public int deleteUserCourse(String courseName) {
        return courseMapper.deleteUserCourse(courseName);
    }

    @Override
    public CourseDO selectById(Integer courseNo) {
        return courseMapper.selectById(courseNo);
    }

    @Override
    public int update(CourseDO courseDO) {
        return courseMapper.update(courseDO);
    }

    @Override
    public List<UserDO> getTeacher() {
        return courseMapper.getTeacher();
    }

    @Override
    public String getNameById(Integer id) {
        return courseMapper.getNameById(id);
    }

    @Override
    public int insertUserCourse(UserCourseDo userCourseDo) {
        return courseMapper.insertUserCourse(userCourseDo);
    }

    @Override
    public CourseDO selectCourseByCid(String courseName) {
        return courseMapper.selectCourseByCid(courseName);
    }

    @Override
    public CourseDO selectCourseByNo(String courseNo) {
        return courseMapper.selectCourseByNo(courseNo);
    }
}
